package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.constant.MessageConstant;
import com.atguigu.entity.Result;
import com.atguigu.pojo.OrderSetting;
import com.atguigu.service.OrderSettingService;
import com.atguigu.util.POIUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/OrderSetting")
public class OrderSettingController {

    @Reference
    OrderSettingService orderSettingService;

    @PostMapping("/upload")
    public Result upload(MultipartFile excelFile) throws Exception {

        try {
            List<String[]> strings = POIUtils.readExcel(excelFile);
            List<OrderSetting> list = new ArrayList<>();
            for (String[] arr : strings) {
                OrderSetting orderSetting = new OrderSetting();
                orderSetting.setOrderDate(new Date(arr[0]));
                orderSetting.setNumber(Integer.parseInt(arr[1]));
                list.add(orderSetting);
            }
            orderSettingService.addOrUpdate(list);
            return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        }
    }

    @GetMapping("/findPage")
    public Result findPage(String date){
        try {
            List<Map<String, Integer>> list = orderSettingService.findPage(date);
            return new Result(true,MessageConstant.GET_ORDERSETTING_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }

    @PostMapping("/addOrUpdateOrderSetting")
    public Result addOrUpdateOrderSetting(@RequestBody OrderSetting orderSetting){
        try {
            orderSettingService.addOrUpdateOrderSetting(orderSetting);
            return new Result(true,MessageConstant.ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ORDERSETTING_FAIL);
        }
    }

}
